package com.dao;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.entity.Message;
import com.util.DBHelp;
import com.util.RowMapper;

public class MessageDao {
	
	DBHelp<Message> help=new DBHelp<Message>();
	
	public void add(Message message) {
		String sql="INSERT INTO `t_message`(`id`,`content`,`createtime`,`projectid`,`employeeid`) VALUES(?,?,?,?,?)";
		help.executeSQL(sql, message.getId(),message.getContent(),message.getCreatetime(),message.getProjectid(),message.getEmployeeid());
	}

	public List<Message> getByPid(String id) {
		String sql="SELECT `id`,`content`,`createtime`,`projectid`,`employeeid` FROM `t_message` WHERE `projectid`=? ORDER BY `createtime` DESC";
		return help.executeQueryForList(sql, new Mapper(), id);
	}
	
	public Message getByContent(String content) {
		String sql="SELECT `id`,`content`,`createtime`,`projectid`,`employeeid` FROM `t_message` WHERE `content`=?";
		return help.executeQueryForObject(sql, new Mapper(), content);
	}
	
	public List<Message> getNewMessage(String createtime,String projectid) {
		String sql="SELECT `id`,`content`,`createtime`,`projectid`,`employeeid` FROM `t_message` WHERE `createtime`>? and `projectid`=? ORDER BY `createtime`";
		return help.executeQueryForList(sql, new Mapper(), createtime,projectid);
	}
	
	public List<Message> getPage(int page) {
		String sql="SELECT * FROM`t_message` ORDER BY `createtime` DESC LIMIT ?,5";
		return help.executeQueryForList(sql, new Mapper(), page);
	}
	
	public int getPageNum(String id){
		String sql="SELECT COUNT(*) FROM `t_message` WHERE `projectid`='"+id+"';";
		return Integer.parseInt(help.query(sql));
	}
	
	private class Mapper implements RowMapper<Message>{

		public Message mapperRow(ResultSet rs) throws SQLException {
			Message message=new Message();
			message.setContent(rs.getString("content"));
			message.setCreatetime(rs.getString("createtime"));
			message.setEmployeeid(rs.getString("employeeid"));
			message.setId(rs.getString("id"));
			message.setProjectid(rs.getString("projectid"));
			
			return message;
		}
		
	}

}
